package com.zzyl.framework.interceptor;/**
 * @author wl
 * @version 1.0
 * @since 2025-08-18 15:39
 */

import cn.hutool.core.map.MapUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *des:
 *data Created in 2025-08-18 15-39
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    //有参构造器
    public MemberInterceptor(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //如果不是controller层的请求， 直接放行
       if (!(handler instanceof HandlerMethod)){
           return true;
       }
       //1.获取header中的token
        String token = request.getHeader("authorization");
        //2.判断token是否存在，如果不存在，响应401
        if (StringUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }
        //3.如果token存在，解析token
        Claims claims = tokenService.parseToken(token);
        //判断claims是否为空，如果为空，响应401
        if (ObjectUtils.isEmpty(claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //4.解析token中的数据
        Long userId = MapUtil.get(claims, "userId", Long.class);
        //5.判断数据是否为空，如果为空，响应401
        if (ObjectUtils.isEmpty(userId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("认证失败");
        }

        //6.将用户id放入threadlocal中
        UserThreadLocal.set(userId);

        return true;
    }





    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
